package cn.tedu.blackhorse.service.impl;

import cn.tedu.blackhorse.ex.ServiceCode;
import cn.tedu.blackhorse.ex.ServiceException;
import cn.tedu.blackhorse.mapper.CourseMapper;
import cn.tedu.blackhorse.mapper.OrderMapper;
import cn.tedu.blackhorse.mapper.StudentMapper;
import cn.tedu.blackhorse.mapper.TeacherMapper;
import cn.tedu.blackhorse.pojo.dto.OrderAddNewDTO;
import cn.tedu.blackhorse.pojo.entity.Order;
import cn.tedu.blackhorse.pojo.vo.CourseStandardVO;
import cn.tedu.blackhorse.pojo.vo.OrderListItemVO;
import cn.tedu.blackhorse.pojo.vo.OrderStandardVO;
import cn.tedu.blackhorse.pojo.vo.StudentStandardVO;
import cn.tedu.blackhorse.service.IOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private CourseMapper courseMapper;
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private OrderMapper orderMapper;

    @Override
    public void insertOrder(OrderAddNewDTO orderAddNewDTO) {
        CourseStandardVO course = courseMapper.getById(orderAddNewDTO.getCourseId());
        if (course == null){
            String message = "添加失败,购买的课程不存在";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        StudentStandardVO student = studentMapper.getById(orderAddNewDTO.getStudentId());
        if (student == null){
            String message = "添加失败,购买的课程不存在";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        Order order = new Order();
        order.setCourseId(orderAddNewDTO.getCourseId());
        order.setStudentId(orderAddNewDTO.getStudentId());
        int row = orderMapper.insert(order);
        if (row != 1){
            String message = "添加失败,系统繁忙,请稍后重试";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_INSERT,message);
        }
    }

    @Override
    public void deleteOrder(Long id) {
        OrderStandardVO order = orderMapper.getById(id);
        if (order == null){
            String message = "删除失败,查询的订单未找到";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        int row = orderMapper.deleteById(id);
        if (row != 1){
            String message = "删除失败,系统繁忙,请稍后重试";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_DELETE,message);
        }
    }

    @Override
    public List<OrderListItemVO> list() {
        return orderMapper.list();
    }
}
